import React, { useEffect, useState } from 'react'

const App = () => {
	const [plants,setPlants] = useState([]);
	const [colPlants,setColPlants] = useState([]);
	useEffect(()=>{
		fetch('https://www.fastmock.site/mock/3c02a69b3952632e311022710cb48a6c/plant/getPlants')
			.then(res=>res.json())
			.then(res=>{
				res.result.plantList.filter(item=>{
					item.isCollect=false;
					return item
				})
				setPlants(res.result.plantList)
			})
	},[])
	const collection = (id,name)=>{
		setColPlants([{plantID:id,name},...colPlants])
		setPlants(plants.filter(item=>{
			if(item.plantID===id){
				item.isCollect=true
			}
			return item
		}))
	}
	const cancelCollection = (id)=>{
		setColPlants(colPlants.filter(item=>item.plantID!==id))
		setPlants(plants.filter(item=>{
			if(item.plantID===id){
				item.isCollect=false
			}
			return item
		}))
	}
	return (
		<div className='list'>
			<div className='head'>
				<h1>收藏列表</h1>
				<ul className='collist'>
					{
						colPlants.map(item=>
							<div key={item.plantID}>
								<li>{item.name}</li>
								<button onClick={()=>{cancelCollection(item.plantID)}}>取消收藏</button>
							</div>
						)
					}
				</ul>
			</div>
			<div className='plants'>
				<h1>鲜花列表</h1>
				<div className='flowers'>
					{
						!plants || plants.map(item=>{
							return (
								<div key={item.plantID} className="box">
									<img src={item.coverURL}/>
									<span>{item.name}</span>
									<span>{item.engName}</span>
									<span>
										{item.area || "未知产地"} 
									</span>
									<button onClick={()=>collection(item.plantID,item.name)}>{item.isCollect?"已收藏":"收藏"}</button>
								</div>
							)
						})
					}
				</div>
			</div>
		</div>
	)
}

export default App;